package net.tycmc.cty.ctyms.timejob.iems.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import net.tycmc.cty.ctyms.timejob.common.DateControl;
import net.tycmc.cty.ctyms.timejob.iems.dao.ChangeInstallRecordDao;

import com.tycmc.functions.util.MapGetter;
import com.tycmc.functions.util.StringUtil;

public class ChangeInstallRecordRunner implements Runnable {
	private Map<String,Object>param;
	private ChangeInstallRecordDao cird;
	private CountDownLatch cdlc;
	public ChangeInstallRecordRunner(Map<String, Object> param,ChangeInstallRecordDao chird,CountDownLatch threadsSignal) {
		this.param = param;
		this.cird=chird;
		this.cdlc=threadsSignal;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//设备id
		try{
			String vclid=MapGetter.getString(param,"vehicleid");
			//开始时间（换更时间）
			String beginmsgtime=MapGetter.getString(param,"msgtime");
			//结束时间
			String endmsgtime=MapGetter.getString(param,"endmsgtime");
			//上一次发动机序列号
			String preesn=MapGetter.getString(param,"preesn");
			//判断时间差
			if(!StringUtil.isValid(endmsgtime)){
				endmsgtime=DateControl.AddMiaoShu(beginmsgtime,300);
				param.put("endmsgtime",endmsgtime);
			}else{
				long dateDeff=DateControl.getMiaoShu(beginmsgtime,endmsgtime);
				if(dateDeff>300){//如果超出5分钟
					endmsgtime=DateControl.AddMiaoShu(beginmsgtime,300);
					param.put("endmsgtime",endmsgtime);
				}
			}
			//根据设备id获取现性故障
			List<Map<String,Object>>listHappening=cird.getAllHappeningFltInChangeInstall(param);
			//现行故障串
			String happingflt=dealFlt(listHappening);
			param.put("happingflt", happingflt);
			//根据设备id获取非现性故障
			List<Map<String,Object>>no_listHappening=cird.getAllNo_HappeningFltInChangeInstall(param);
			//非现行故障串
			String no_happingflt=dealFlt(no_listHappening);
			param.put("no_happingflt", no_happingflt);
			if(!StringUtil.isValid(preesn)){
				//从业务表中，获取这台车上一次的发动机序列号
				Map<String,Object>mapresult=cird.getLastESN(vclid);
				if(null!=mapresult&&mapresult.size()>0){
					preesn=MapGetter.getString(mapresult,"Esncr_changeLatEsn");
					param.put("preesn",preesn);
				}
			}
			//开始存储数据
			cird.saveInstallRecord(param);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			cdlc.countDown();
		}
		
	}
	/**
	 * 处理现行故障
	 * @param list
	 * @return
	 */
	private String dealFlt(List<Map<String,Object>>list){
		String fltCodeString="";
		if(null!=list&&list.size()>0){
			for(Map<String,Object>map:list){
				String fltCode=MapGetter.getString(map, "SysISM_Code");
				fltCodeString+=fltCode+",";
			}
			fltCodeString=fltCodeString.substring(0,fltCodeString.length()-1);
		}
		return fltCodeString;
	}
}
